# (1)
# 题目描述：
# 通过OpenCV读取一张图片，完成下面的操作：
#
# (2)
# 题目要求：.
# ①　导入相关头文件
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

spr = 3
spc = 5
spn = 0
plt.figure(figsize=[12, 6])


def my_show_img(img, title, trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    plt.title(title)
    plt.axis('off')
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)


# ②　读入一张图片并转为灰度图
path = '../../../../large_data/CV2/exam/day14/text_pic.png'
img = cv.imread(path, cv.IMREAD_GRAYSCALE)
print('img.shape', img.shape)
my_show_img(img, 'gray', cmap='gray')

# ③　将图像转变为二值图
ret, bin = cv.threshold(img, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY_INV)

# ④　显示二值化图结果
my_show_img(bin, 'bin', cmap='gray')

# ⑤　自定义卷积核
kernel = np.ones([3, 3], dtype=np.uint8)

# ⑥　完成形态学变换
closing = cv.morphologyEx(bin, cv.MORPH_CLOSE, kernel, iterations=1)
my_show_img(closing, 'closing', cmap='gray')

# ⑦　进行水平方向的投影
# ⑧　得到水平方向的分割范围
# ⑨　进行垂直方向的投影
# ⑩　得到垂直方向的分割范围
# 11　完成行分割
# 12　完成字符的分割
contours, hierarchy = cv.findContours(closing, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
bg = cv.cvtColor(closing, cv.COLOR_GRAY2BGR)
bg_ = bg.copy()
cv.drawContours(bg, contours, -1, (0, 255, 0), 1)
my_show_img(bg, 'contours', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
for c in contours:
    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(bg_, (x, y), (x + w, y + h), (0, 255, 0), 1)
my_show_img(bg_, 'rectangles', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

i = 20
while True:
    if spn > spr * spc - 1:
        break
    i += 1
    x, y, w, h = cv.boundingRect(contours[i])
    char = img[y:y + h, x:x + w]
    my_show_img(char, 'char #' + str(i), lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

# 13　加入必要注释

# Show all plotting
plt.show()
